<?php
/**
 * User: kong
 * Date: 2023/12/7
 * Time: 15:48
 */

namespace App\Service;


class LogService
{
    /**
     * Notes:写入日志
     * @param string $filename 日志文件名
     * @param string $msg 日志消息
     * User: kong
     * Date: 2023/12/13
     * @param string $level
     * @throws \Exception
     */
    public static function writeLog(string $filename,string $msg,string $level = 'info'): void
    {
        $time = time();
        $date = date("Ym");
        $dir = 'runtime/logs/'.$date.'/';
        if (!is_dir($dir)){
            mkdir($dir,0777,true);
        }
        $logFile = $dir.date("d",$time).'.log';
        if (empty(!$filename)){
            $logFile = $dir.$filename."-".date("d").'.log';
        }
        //如果是新建的日志文件，去掉内容中的第一个字符逗号
        $datetime = "[".date("Y-m-d H:i:s")."]";
        $levelRange = ["info","error","warning"];
        if (!in_array($level,$levelRange)){
            throw new \Exception("日志级别错误",\App\Constants\ErrorCode::PARAM_ERROR);
        }
        $level = " log.".strtoupper($level).": ";
        if(file_exists($logFile) && abs(filesize($logFile))>0){
            $content = "\n".$datetime.$level.$msg;
        }else{
            $content = $datetime.$level.$msg;
        }
        //往日志文件内容后面追加日志内容
        file_put_contents($logFile, $content, FILE_APPEND);
    }
}
